package demo23;

public class Sort2 {
    public void mergeSort(int[] array){
        mergeSortTemp(array,0,array.length-1);
    }
    public void mergeSortTemp(int[]array,int left,int right){
        if(left>=right){
            return;
        }
        int mid=(left+right)/2;
        //分组
        mergeSortTemp(array,left,mid);
        mergeSortTemp(array,mid+1,right);
        merge(array,left,mid,right);//合并两个有序数组
    }
    //归并排序
    public void merge(int[]array,int left,int mid,int right){
        int s1=left;
        int e1=mid;
        int s2=mid+1;
        int e2=right;
        int k=0;
        int[]temp=new int[right-left+1];
        while (s1<=e1&&s2<=e2){
            if(array[s1]<=array[s2]){
                temp[k++]=array[s1++];
            }else{
                temp[k++]=array[s2++];
            }
        }
        while (s1<=e1){
            temp[k++]=array[s1++];
        }
        while(s2<=e2){
            temp[k++]=array[s2++];
        }
        for(int i=0;i<k;i++){
            array[i+left]=temp[i];
        }
    }
    //非递归实现归并排序
    public void mergeSortNor(int[]array){
        int gap=1;
        while(gap<array.length){
            for(int i=0;i<array.length-1;i=i+gap*2){
                int left=i;
                int mid=left+gap-1;
                int right=mid+gap;
                if(mid>=array.length){
                    mid=array.length-1;
                }
                if(right>=array.length){
                    right=array.length-1;
                }
                merge(array,left,mid,right);
            }
            gap=gap*2;
        }
    }
}
